<?php

require_once 'facebook/facebook.php';
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Facebook
 *
 * @author minhhq
 */
class MKT_Facebook extends Facebook {

    private $_has_new_signal;
    /**
     *
     * @var MKT_Facebook
     */
    private static $_instance;

    /**
     * 
     * @var ArrayObject
     */
    private $_user_pages;

    public function __construct() {
        $facebook_config = $this->getConfig();
        $params = array(
            'appId' => $facebook_config['params']['appId'],
            'secret' => $facebook_config['params']['secret']
        );
        return parent::__construct($params);
    }

    public static function getInstance() {
        if (!self::$_instance) {
            self::$_instance = new MKT_Facebook();
        }
        return self::$_instance;
    }

    public function getConfig() {
        $config = MKT_Util::getConfig("facebook");
        return $config;
    }

    public function getScope() {
        $config = $this->getConfig();
        $scope = $config['params']['scope'];
        return $scope;
    }

    public function getAppUrl() {
        $config = $this->getConfig();
        return $config['params']['app_url'];
    }

    public function getAppTabUrl($id_social_page) {
        return FACEBOOK_URL . "/$id_social_page?sk=app_{$this->getAppId()}";
    }

    public function getBatchData($id_socials, $params) {
        $batch_request = array();

        foreach ($id_socials as $id_social) {
            $batch_request_item = array(
                "method" => "GET",
                "relative_url" => urlencode("$id_social?$params")
            );
            $batch_request[] = $batch_request_item;
        }
        $json_batch_request = json_encode($batch_request);
        $params = array('access_token' => $this->getAccessToken());
        
        $fb_results = $this->api("?batch=$json_batch_request", "POST", $params);
        $result = array();
        for ($i = 0; $i < sizeof($id_socials); $i++) {
            $fb_result = $fb_results[$i];
            $id_social = $id_socials[$i];

            $data = NULL;

            if (!empty($fb_result) && ($fb_result['code'] == SUCCESSFUL_BATCH_CODE)) {
                $data = json_decode($fb_result['body'], true);
            }
            $result[$id_social] = $data;
        }
        return $result;
    }

    public function getUserPages() {
        if ($this->_user_pages == null) {
            $id_user = $this->getUser();
            if (!empty($id_user)) {
                try {
                    $accounts = $this->api('/me/accounts');
                    $this->_user_pages = $accounts['data'];
                    if (!empty($this->_user_pages)) {
                        foreach ($this->_user_pages as $key => $page) {
                            if ($page['category'] == 'Application') {
                                unset($this->_user_pages[$key]);
                            }
                        }
                    }
                } catch (FacebookApiException $e) {
                    $log = Zend_Registry::get("log");
                    $log->log("{$e->getMessage()} when getting user pages", 0);
                }
            } else {
                $this->_user_pages = array();
            }
        }
        return $this->_user_pages;
    }

    public function getPageAccessToken($id_social_page) {
        $user_pages = $this->getUserPages();
        $result = NULL;
        if (!empty($user_pages)) {
            foreach ($user_pages as $user_page) {
                if ($user_page['id'] == $id_social_page) {
                    $result = $user_page['access_token'];
                }
            }
        }
        return $result;
    }

    public function registerRealtimeUpdate($id_social_page) {
        $page_access_token = $this->getPageAccessToken($id_social_page);
        $params = array(
            'access_token' => $page_access_token,
            'app_id' => $this->getAppId()
        );
        $this->api("/$id_social_page/tabs", "POST", $params);
    }

    public function hasAuthorized() {
        $result = true;
        $user = $this->getUser();
        if (empty($user)) {
            $result = false;
        } else {
            $params = array("access_token" => $this->getAccessToken());
            $permissions = $this->api("/me/permissions", $params);
            if (isset($permissions['data']) && sizeof($permissions['data']) > 0) {
                $permissions = $permissions['data'][0];
                $scopes = explode(",", $this->getScope());
                foreach ($scopes as $scope) {
                    if ((!isset($permissions[$scope])) || $permissions[$scope] != 1) {
                        $result = false;
                    }
                }
            }
        }
        return $result;
    }
    
    public function getAvatar($id_social, $width = DEFAULT_IMAGE_WIDTH, $height = DEFAULT_IMAGE_HEIGHT) {
        return GRAPH_URL . "/$id_social/picture?width=$width&height=$height";
    }
    
    public function getCover($id_social) {
        $result = NULL;
        try {
            $cover_data = $this->api("/$id_social?fields=cover");
            if (isset($cover_data['cover'])) {
                $result = array (
                    'source'   => $cover_data['cover']['source'],
                    'offset_y' => $cover_data['cover']['offset_y']
                );
            } else {
                $result = array (
                    'source'   => FB_NO_IMAGE,
                    'offset_y' => 0
                );
            }
        } catch (Exception $e) {
            $log = Zend_Registry::get("log");
            $log->log("{$e->getMessage()} when getting cover photo of $id_social", 0);
            $result = array (
                    'source'   => FB_NO_IMAGE,
                    'offset_y' => 0
            );
        }
        return $result;
    }
      
    protected function getSignedRequestPageParam($tag) {
        $signed_request = $this->getSignedRequest();
        if (!empty($signed_request)) {
            return $signed_request['page'][$tag];
        } else {
            return NULL;
        }
    }
    
    public function getIdPage() {
        return $this->getSignedRequestPageParam('id');
    }

    public function isAdmin() {
        return $this->getSignedRequestPageParam('admin');
    }
    
    public function hasLikedPage() {
        return $this->getSignedRequestPageParam('liked');
    }
    
    /**
     * 
     * @return boolean
     */
    public function hasNewSignal() {
        if ($this->_has_new_signal !== NULL) {
            return $this->_has_new_signal;
        }
        if ($this->hasNewSignedRequest()) {
            return true;
        }
        if (isset($_REQUEST['code']) && isset($_REQUEST['state'])) {
            if (($this->getPersistentData('code') != $_REQUEST['code']) &&
                    ($this->getPersistentData('state') != $_REQUEST['state'])) {
                return true;
            }
        }
        return false;
    }
    
	/**
     * 
     * @return boolean
     */
    public function hasNewSignedRequest() {
        $session = Zend_Registry::get('session');
        $arrSignedRequests = $this->getSignedRequest();
        $temp = $session->{$this->getSignedRequestCookieName()};
        
        /* @var $session Zend_Session_Namespace */
        if (!empty($arrSignedRequests['expires']) && 
            $session->{$this->getSignedRequestCookieName()} != $arrSignedRequests['expires']) {
            $session->{$this->getSignedRequestCookieName()} = $arrSignedRequests['expires'];
            return true;
        }
        return false;
    }

    public function handleUserAccessTooken($user) {
        if ($this->getApplicationAccessToken() !== $this->getAccessToken()) {
            if ($user->extended_access_token !== $this->getAccessToken()) {
                if ($this->setExtendedAccessToken() !== false) {
                    if ($user->updateAccessToken($this->getPersistentData('access_token'))) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    public function getUserProfile() {
        try {
            $result = $this->api("/me");
            return $result;
        } catch (Exception $e) {
            if (Core_Util::isDebugMode()) {
                Zend_Debug::dump($e);
            }
            $log = Zend_Registry::get("log");
            $log->log("{$e->getMessage()} when getting user profile", 0);
        }
    }
    
    public function url($url) {
        if (substr($url, 0, 4) == 'http') {
            return $url;
        } else {
            return $this->getAppUrl() . $url;
        }
    }
    
    public function getShareUrl($id_social_page) {
        return $this->url("/default/index/share/pid/$id_social_page");
    }

}
?>
